<?php

use think\App;
use think\facade\Db;
use think\facade\Config;
use think\admin\Library;

// 定义应用目录
define('APP_PATH', __DIR__ . '/app/');
define('ROOT_PATH', __DIR__ . '/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

// 加载基础文件
require __DIR__ . '/vendor/autoload.php';

// 手动初始化应用
$app = new App();
$app->setNamespace('app');
$app->setRuntimePath(RUNTIME_PATH);

// 手动设置Library::$sapp
Library::$sapp = $app;

// 手动加载配置文件
try {
    Config::set(include __DIR__ . '/config/app.php', 'app');
    Config::set(include __DIR__ . '/config/database.php', 'database');
} catch (\Exception $e) {
    echo "Error loading configuration files: " . $e->getMessage() . "\n";
    exit(1);
}

// 初始化应用
try {
    $app->initialize();
} catch (\Exception $e) {
    echo "Error initializing application: " . $e->getMessage() . "\n";
    exit(1);
}

// 设置表前缀
try {
    $tablePrefix = Config::get('database.connections.mysql.prefix');
    echo "Table prefix: $tablePrefix\n";
} catch (\Exception $e) {
    echo "Error getting table prefix: " . $e->getMessage() . "\n";
    exit(1);
}

// 执行安装逻辑
try {
    // 创建数据库表
    Db::execute("CREATE TABLE IF NOT EXISTS `{$tablePrefix}parking_company` (
        `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(255) NOT NULL,
        `location` VARCHAR(255) NOT NULL,
        `employee_count` INT DEFAULT NULL,
        `free_parking_hours` INT NOT NULL DEFAULT 0,
        `max_employee_vehicles` INT NOT NULL DEFAULT 0,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `status` TINYINT(1) NOT NULL DEFAULT 1
    )");

    Db::execute("CREATE TABLE IF NOT EXISTS `{$tablePrefix}parking_employee` (
        `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `company_id` INT UNSIGNED NOT NULL,
        `name` VARCHAR(255) NOT NULL,
        `plate_number` VARCHAR(255) NOT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `status` TINYINT(1) NOT NULL DEFAULT 1,
        FOREIGN KEY (`company_id`) REFERENCES `{$tablePrefix}parking_company`(`id`) ON DELETE CASCADE
    )");

    Db::execute("CREATE TABLE IF NOT EXISTS `{$tablePrefix}parking_parking` (
        `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `plate_number` VARCHAR(255) NOT NULL,
        `entry_time` TIMESTAMP NOT NULL,
        `exit_time` TIMESTAMP NULL,
        `free_hours` INT NOT NULL DEFAULT 0,
        `fee` DECIMAL(10, 2) DEFAULT NULL,
        `is_paid` TINYINT(1) NOT NULL DEFAULT 0,
        `payment_time` TIMESTAMP NULL,
        `previous_record_id` INT UNSIGNED DEFAULT NULL,
        `type` TINYINT(1) NOT NULL DEFAULT 3,
        `is_exited` TINYINT(1) NOT NULL DEFAULT 1,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (`previous_record_id`) REFERENCES `{$tablePrefix}parking_parking`(`id`)
    )");

    Db::execute("CREATE TABLE IF NOT EXISTS `{$tablePrefix}parking_visitor` (
        `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `company_id` INT UNSIGNED NOT NULL,
        `plate_number` VARCHAR(255) NOT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `free_hours` INT NOT NULL,
        `parking_record_id` INT UNSIGNED NOT NULL,
        FOREIGN KEY (`company_id`) REFERENCES `{$tablePrefix}parking_company`(`id`) ON DELETE CASCADE,
        FOREIGN KEY (`parking_record_id`) REFERENCES `{$tablePrefix}parking_parking`(`id`)
    )");

    // 插入菜单项
    $menuItems = [
        [
            'pid'        => 0,
            'title'      => '停车管理',
            'icon'       => 'fa fa-car',
            'url'        => '',
            'target'     => '_self',
            'sort'       => 100,
            'status'     => 1,
            'children'   => [
                [
                    'title'   => '公司管理',
                    'icon'    => 'fa fa-building',
                    'url'     => 'parking/admin.company/index',
                    'sort'    => 1,
                    'status'  => 1,
                ],
                [
                    'title'   => '员工管理',
                    'icon'    => 'fa fa-users',
                    'url'     => 'parking/admin.employee/index',
                    'sort'    => 2,
                    'status'  => 1,
                ],
                [
                    'title'   => '停车记录管理',
                    'icon'    => 'fa fa-history',
                    'url'     => 'parking/admin.parking/index',
                    'sort'    => 3,
                    'status'  => 1,
                ],
                [
                    'title'   => '访客管理',
                    'icon'    => 'fa fa-address-book',
                    'url'     => 'parking/admin.visitor/index',
                    'sort'    => 4,
                    'status'  => 1,
                ],
            ],
        ],
    ];

    foreach ($menuItems as $item) {
        addMenuItem($item);
    }

    echo "Installation completed successfully.\n";
} catch (\Exception $e) {
    echo "Error during installation: " . $e->getMessage() . "\n";
}

function addMenuItem($item, $pid = 0)
{
    $menu = [
        'pid'        => $pid,
        'title'      => $item['title'],
        'icon'       => $item['icon'],
        'url'        => $item['url'],
        'target'     => $item['target'] ?? '_self',
        'sort'       => $item['sort'],
        'status'     => $item['status'],
    ];
    $menuId = Db::name('system_menu')->insertGetId($menu);

    if (isset($item['children']) && is_array($item['children'])) {
        foreach ($item['children'] as $child) {
            addMenuItem($child, $menuId);
        }
    }
}
